package com.topscore.uke.database;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.SelectIterator;
import com.j256.ormlite.stmt.Where;
import com.topscore.uke.database.entities.SearchHistoryItem;
import com.topscore.uke.main.BaseApplication;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by 71468 on 2018/3/20.
 */

public class SearchHistoryDAO {
    private Dao<SearchHistoryItem, String> mDao;
    private static SearchHistoryDAO instance;

    public synchronized static SearchHistoryDAO getInstance() {
        if (instance == null) {
            instance = new SearchHistoryDAO();
        }
        return instance;
    }

    public boolean creatOrUpdate(SearchHistoryItem item) {
        Dao<SearchHistoryItem, String> dao = getInstance().getDao();
        try {
            Where where = dao.queryBuilder().where();
            List<SearchHistoryItem> list = where.and(
                    where.eq("loginName", item.getLoginName()), where.eq("word", item.getWord())
            ).query();
            if (list == null || list.isEmpty()) {
                return dao.createOrUpdate(item).getNumLinesChanged() > 0;
            } else {
                dao.delete(list);
                return dao.createOrUpdate(item).getNumLinesChanged() > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<SearchHistoryItem> searchHistories(String loginName) {
        List<SearchHistoryItem> list = null;
        Dao<SearchHistoryItem, String> dao = getInstance().getDao();
        QueryBuilder<SearchHistoryItem, String> queryBuilder = dao.queryBuilder();
        Where<SearchHistoryItem, String> where = queryBuilder.orderBy("id", false).where();
        try {
            list = where.eq("loginName", loginName).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public int deleteSearchList(String loginName) {
        Dao<SearchHistoryItem, String> dao = getInstance().getDao();
        try {
            List<SearchHistoryItem> list = dao.queryBuilder().where().eq("loginName", loginName).query();
            return dao.delete(list);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public Dao<SearchHistoryItem, String> getDao() {
        if (mDao == null) {
            try {
                mDao = BaseApplication.getDataBaseHelper().getDao(SearchHistoryItem.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return mDao;
    }
}
